package com.consult.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.consult.config.dto.AjaxResult;
import com.consult.entity.Appointment;
import com.consult.entity.RegisterRecord;
import com.consult.service.IAppointmentService;
import com.consult.service.IDutyService;
import com.consult.service.IRegisterRecordService;
import com.consult.utils.TokenUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * ԤԼ 前端控制器
 * </p>
 *
 * @author ${author}
 * @since 2021-06-22
 */
@RestController
@RequestMapping("/appointment")
public class AppointmentController {

    @Resource
    private IDutyService dutyService;
    @Resource
    private IAppointmentService appointmentService;
    @Resource
    private IRegisterRecordService recordService;

    @PostMapping("/add")
    public AjaxResult addAppointment(@RequestBody Appointment appointment, HttpServletRequest request) {
        int i = DateUtil.thisHour(true);
        if (i > 16) {
            return AjaxResult.error("预约失败,请在下午四点前预约");
        }
        // 判断是否登记
        Long userId = TokenUtil.getUserId(request);
        if (recordService.getUserRecordNum(userId) < 1) {
            return AjaxResult.error("预约失败,请先登记");
        }
        //
        int appNum = dutyService.getNumByUserId(appointment.getUserId());
        int appedNum = appointmentService.getAppNum(appointment.getUserId());
        if (appedNum>= appNum) {
            return AjaxResult.error("预约失败,预约已满");
        }
        appointment.setStuId(userId);
        appointmentService.save(appointment);
        return AjaxResult.success("预约成功");
    }

    @PostMapping("/page")
    public AjaxResult getAppointmentPage(@RequestBody Page<Appointment> page) {
        page = appointmentService.getAppointmentPage(page);
        return AjaxResult.success(page);
    }
}

